package com.vincent.sms;

import android.Manifest;
import android.app.Service;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Telephony;
import android.telephony.SmsManager;

import java.util.ArrayList;

/**
 * projectName:          Sms
 * packageName:          com.vincent.sms
 * className:            HeadlessSmsSendService
 * author:               Luoxiang
 * time:                 2025/6/29	10:44
 * desc:                 TODO
 * <p>
 * svnVersion:
 * upDateAuthor:         a
 * upDate:               2025/6/29
 * upDateDesc:           TODO
 */
public class HeadlessSmsSendService extends Service {
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 处理发送短信的请求
        handleSendSms(intent);

        // 服务完成后自动停止
        stopSelf(startId);

        return START_NOT_STICKY;
    }

    private void handleSendSms(Intent intent) {

        // 获取消息内容和收件人
        Bundle extras = intent.getExtras();
        if (extras == null) {
            return;
        }

        String message = extras.getString(Intent.EXTRA_TEXT);
        Uri recipientUri = intent.getData();
        String recipient = recipientUri.getSchemeSpecificPart();

        // 确保我们有必要的权限
        if (checkSelfPermission(Manifest.permission.SEND_SMS)
                != PackageManager.PERMISSION_GRANTED) {
            // 没有权限，无法发送
            return;
        }

        // 发送短信
        SmsManager smsManager = SmsManager.getDefault();
        ArrayList<String> parts = smsManager.divideMessage(message);

        if (parts.size() > 1) {
            smsManager.sendMultipartTextMessage(recipient, null, parts, null, null);
        } else {
            smsManager.sendTextMessage(recipient, null, message, null, null);
        }

        // 将发送的短信记录到短信数据库中
        ContentValues values = new ContentValues();
        values.put(Telephony.Sms.ADDRESS, recipient);
        values.put(Telephony.Sms.BODY, message);
        values.put(Telephony.Sms.DATE, System.currentTimeMillis());
        values.put(Telephony.Sms.READ, 1);
        values.put(Telephony.Sms.TYPE, Telephony.Sms.MESSAGE_TYPE_SENT);

        getContentResolver().insert(Telephony.Sms.Sent.CONTENT_URI, values);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
